package com.aier.entrance.common;

import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TimerTask;

import javax.annotation.Resource;

import com.aier.entrance.entity.EntranceDevice;
import com.aier.entrance.entity.VideoDevice;
import com.aier.entrance.service.IEntranceCardService;

public class VideoHeartbeatCheck extends TimerTask{

    @Resource(name = "entranceCardService")
    private IEntranceCardService entranceCardService;
    
    @Override
    public void run() {
        System.out.println("VideoHeartbeatCheck run:  "+new Timestamp(new java.util.Date().getTime()));
        if(null==EntranceServerData.mapED||EntranceServerData.mapED.size()<=0){
            return;
        }
        Map<String,EntranceDevice> mapED_tmp = new HashMap<String,EntranceDevice>();
        for (Map.Entry<String,EntranceDevice> entry : EntranceServerData.mapED.entrySet()) { 
            if (entry.getValue() != null) { 
                mapED_tmp.put(entry.getKey(), entry.getValue()); 
            } 
        } 
//        System.out.println(mapED_tmp);
//        System.out.println(EntranceServerData.mapED);
        Set<String> set = mapED_tmp.keySet();
        System.out.println("mapED.size:"+mapED_tmp.size()+",mapED.keySet:"+set.toString());
        for(String key:set){
            EntranceDevice ed=mapED_tmp.get(key);
            VideoDevice vd=ed.getVd();
            if(null==vd){
                continue;
            }
            try {
                URL u = new URL(vd.getUrl());
                URLConnection uc = u.openConnection();
                uc.getContentType();
                String newIP = uc.getURL().toString();
                String urlIP = vd.getUrlIP();
                if(!newIP.equals(urlIP)){
                    System.out.println("newIP:"+newIP+",urlIP:"+urlIP);
                    vd.setUrlIP(newIP);
                    entranceCardService.updateVideoUrlIP( vd.getVid(), newIP);
                    System.out.println("vid:"+vd.getVid()+",UrlIP:"+vd.getUrlIP());
                }
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
//        System.out.println("mapED_tmp.keySet()"+mapED_tmp.keySet());
//        System.out.println("EntranceServerData.mapED.keySet()"+EntranceServerData.mapED.keySet());
        if(mapED_tmp.size()==EntranceServerData.mapED.size()){
            EntranceServerData.mapED = mapED_tmp;
//            System.out.println("yes");
        }
        
        
    }

    public void setEntranceCardService(IEntranceCardService entranceCardService) {
        this.entranceCardService = entranceCardService;
    }

}
